//
//  ViewController.m
//  CYAnimation
//
//  Created by 楼楚 on 16/5/4.
//  Copyright © 2016年 Chu Lou. All rights reserved.
//

#import "ViewController.h"
#import "POPNumberAnimation.h"
#import "POPBasicAnimation.h"
#import "GCD.h"
#import "StringAttributeHelper.h"//富文本
#import "UIFont+Fonts.h"
#import "CircleView.h"

@interface ViewController ()<POPNumberAnimationDelegate>

@property (nonatomic, strong) POPNumberAnimation *numberAnimation;
@property (nonatomic, strong) GCDTimer           *timer;
@property (nonatomic, strong) UILabel            *label;
@property (nonatomic, strong) CALayer   *movedMask;
@property (nonatomic) CGPoint startPoint;
@property (nonatomic) CGPoint endPoint;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    [self startDisplaceAnimation];
//    [self startNumberAnimation];
//    [self startCircleAnimation];

//做导航条
//    封装动画类
//    上架名称为 pop动画导航
    
//    [self startCountdownAnimation];
//    [self startPathAnimation];
    [self startSnowAnimation];
}
- (void)startSnowAnimation{
    self.view.backgroundColor = [UIColor blackColor];
    
    CAEmitterLayer *snowEmitter = [CAEmitterLayer layer];
//    设置发射源位置、尺寸大小，发射模式、发射源形状
//发射源设置在view外面，效果逼真一些
    snowEmitter.emitterPosition = CGPointMake(120,-120);
    snowEmitter.emitterSize = self.view.bounds.size;
    snowEmitter.emitterMode  = kCAEmitterLayerSurface;
    snowEmitter.emitterShape = kCAEmitterLayerLine;
//    创建雪花粒子 设置名称
    CAEmitterCell *snowflake = [CAEmitterCell emitterCell];
    snowflake.name = @"snow";
    
//     粒子参数的速度乘数因子
    snowflake.birthRate = 20.0;
    snowflake.lifetime  = 120.0;
    
// 粒子速度
    snowflake.velocity =10.0;
    
// 粒子的速度范围
    snowflake.velocityRange = 10;
    
// 粒子y方向的加速度分量
    snowflake.yAcceleration = 2;
    
// 周围发射角度
    snowflake.emissionRange = 0.5 * M_PI;
    
// 子旋转角度范围
    snowflake.spinRange = 0.25 * M_PI;
    snowflake.contents  = (id)[[UIImage imageNamed:@"snow"] CGImage];
    
// 设置雪花形状的粒子的颜色
//以下设置雪花可以是colorful
//    snowflake.color      = [[UIColor whiteColor] CGColor];
//    snowflake.redRange   = 2.f;
//    snowflake.greenRange = 2.f;
//    snowflake.blueRange  = 2.f;
//设置雪花为纯白
    snowflake.color = [[UIColor whiteColor]CGColor];
    
    snowflake.scaleRange = 0.6f;
    snowflake.scale      = 0.7f;
    
    snowEmitter.shadowOpacity = 1.0;
    snowEmitter.shadowRadius  = 0.0;
    snowEmitter.shadowOffset  = CGSizeMake(0.0, 0.0);
    // 粒子边缘的颜色
    snowEmitter.shadowColor  = [[UIColor whiteColor] CGColor];
    
    // 添加粒子
    snowEmitter.emitterCells = @[snowflake];
    
    // 将粒子Layer添加进图层中
    [self.view.layer addSublayer:snowEmitter];
// 加入遮罩有意想不到的效果
    // 形成遮罩
    UIImage *image      = [UIImage imageNamed:@"alpha"];
//    _movedMask          = [CALayer layer];
//    _movedMask.frame    = (CGRect){CGPointZero, image.size};
//    _movedMask.contents = (__bridge id)(image.CGImage);
//    _movedMask.position = self.view.center;
//    snowEmitter.mask    = _movedMask;
    // 拖拽的View
    UIView *dragView = [[UIView alloc] initWithFrame:(CGRect){CGPointZero, image.size}];
    dragView.center  = self.view.center;
//    [self.view addSubview:dragView];
    
    // 给dragView添加拖拽手势
    UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [dragView addGestureRecognizer:recognizer];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    
    // 拖拽
    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
// 关闭CoreAnimation实时动画绘制(核心)
    [CATransaction setDisableActions:YES];
    _movedMask.position = recognizer.view.center;
    
}
- (void)startPathAnimation{
//    起始点
    self.startPoint = CGPointMake(0, 10);
//    结束点
    self.endPoint = CGPointMake(130, 200);
    UILabel *redlabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 10, 10)];
    redlabel.backgroundColor = [UIColor redColor];
    [self.view addSubview:redlabel];
    
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.path = [self path].CGPath;
    pathAnimation.duration = 4.f;
    pathAnimation.timingFunction       = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    redlabel.center = self.endPoint;
    [redlabel.layer addAnimation:pathAnimation forKey:nil];
}
- (UIBezierPath *)path{
    UIBezierPath* bezierPath = [UIBezierPath bezierPath];
    
    [bezierPath moveToPoint:self.startPoint];
    [bezierPath addLineToPoint:CGPointMake(0, 20)];
     [bezierPath addLineToPoint:CGPointMake(20, 20)];
     [bezierPath addLineToPoint:CGPointMake(20,40)];
     [bezierPath addLineToPoint:CGPointMake(40, 40)];
     [bezierPath addLineToPoint:CGPointMake(40, 60)];
     [bezierPath addLineToPoint:CGPointMake(60, 60)];
     [bezierPath addLineToPoint:CGPointMake(60, 80)];
     [bezierPath addLineToPoint:self.endPoint];
    
    return  bezierPath;
    
}
- (void)startCountdownAnimation{
    POPAnimatableProperty *prop = [POPAnimatableProperty propertyWithName:@"countdown" initializer:^(POPMutableAnimatableProperty *prop) {
        
        prop.writeBlock = ^(id obj, const CGFloat values[]) {
            _label               = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
            _label.textAlignment = NSTextAlignmentCenter;
            _label.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.8];
            _label.center        = self.view.center;
            _label.text = [NSString stringWithFormat:@"%02d:%02d:%02d",(int)values[0]/60,(int)values[0]%60,(int)(values[0]*100)%100];
        };
    }];
    [self.view addSubview:_label];
    POPBasicAnimation *anBasic = [POPBasicAnimation linearAnimation];   //秒表当然必须是线性的时间函数
    anBasic.property = prop;    //自定义属性
    anBasic.fromValue = @(0);   //从0开始
    anBasic.toValue = @(3*60);  //180秒
    anBasic.duration = 3*60;    //持续3分钟
    anBasic.beginTime = CACurrentMediaTime() + 1.0f;    //延迟1秒开始
    [_label pop_addAnimation:anBasic forKey:@"countdown"];}

-(void)startCircleAnimation{
    
    CGFloat gapFromTop = 64.f + 20;
    CGFloat width      = self.view.bounds.size.width;
    
    CGFloat halfWidth  = width / 2.f;
    CGFloat radius     = width / 3.f + 20;
    
    CGPoint point1     = CGPointMake(halfWidth / 2.f, gapFromTop + halfWidth / 2.f);
    CGPoint point2     = CGPointMake(halfWidth / 2.f + halfWidth, gapFromTop + halfWidth / 2.f);
    CGPoint point3     = CGPointMake(halfWidth / 2.f, gapFromTop + halfWidth / 2.f + halfWidth);
    CGPoint point4     = CGPointMake(halfWidth / 2.f + halfWidth, gapFromTop + halfWidth / 2.f + halfWidth);
    CircleView *circle1 = [CircleView circleViewWithFrame:CGRectMake(0, 0, radius, radius)
                                               lineWidth:2
                                               lineColor:[UIColor grayColor]
                                               clockWise:YES
                                              startAngle:0];
    
    [circle1 buildView];
    circle1.center = point1;
    [self.view addSubview:circle1];
    self.timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    [self.timer event:^{
        
        CGFloat percent        = arc4random() % 100 / 100.f;
        CGFloat anotherPercent = arc4random() % 100 / 100.f;
        
        // 圆圈1动画
        [circle1 strokeEnd:percent animationType:ElasticEaseInOut animated:YES duration:1.f];
        
       
        
    } timeIntervalWithSecs:1.5f];
    
    [self.timer start];


}
- (void)startDisplaceAnimation{
    UILabel *redSquare = [[UILabel alloc]initWithFrame:CGRectMake(5, 20, 40, 40)];
    redSquare.backgroundColor = [UIColor redColor];
    [self.view addSubview:redSquare];
    POPBasicAnimation *displaceAni = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerPositionX];
    displaceAni.toValue = @(redSquare.center.x +300);
    displaceAni.beginTime = CACurrentMediaTime() + 5.f;
    displaceAni.duration = 0.4f;
    [redSquare pop_addAnimation:displaceAni forKey:@"position"];
}

- (void)startNumberAnimation{
    _label               = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.1];
    _label.center        = self.view.center;
    [self.view addSubview:_label];
    
    self.numberAnimation          = [[POPNumberAnimation alloc] init];
    self.numberAnimation.delegate = self;
    
    __weak ViewController *weakSelf = self;
    self.timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    [self.timer event:^{
        
        // Start animation.
        [weakSelf configNumberAnimation];
        [weakSelf.numberAnimation startAnimation];
        
    } timeIntervalWithSecs:3.f];
    [self.timer start];
}

- (void)configNumberAnimation {
    
    self.numberAnimation.fromValue      = self.numberAnimation.currentValue;
    self.numberAnimation.toValue        = (arc4random() % 101 / 1.f);
    self.numberAnimation.duration       = 2.f;
    self.numberAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.69 :0.11 :0.32 :0.88];
    [self.numberAnimation saveValues];
}
//处理富文本
- (void)POPNumberAnimation:(POPNumberAnimation *)numberAnimation currentValue:(CGFloat)currentValue {
    
    // Init string.
    NSString *numberString = [NSString stringWithFormat:@"%.1f", currentValue];
    NSString *mpsString    = @"mps";
    NSString *totalString  = [NSString stringWithFormat:@"%@ %@", numberString, mpsString];
    
    // Init string ranges.
    NSRange   mpsRange     = [totalString rangeOfString:mpsString];
    NSRange   numberRange  = [totalString rangeOfString:numberString];
    NSRange   totalRange   = NSMakeRange(0, totalString.length);
    
    // Init attributes.
    FontAttribute *totalFont = [FontAttribute new];
    totalFont.font           = [UIFont AvenirLightWithFontSize:20.f];
    totalFont.effectRange    = totalRange;
    
    FontAttribute *numberFont = [FontAttribute new];
    numberFont.font           = [UIFont HYQiHeiWithFontSize:60.f];;
    numberFont.effectRange    = numberRange;
    
    ForegroundColorAttribute *totalColor = [ForegroundColorAttribute new];
    totalColor.color                     = [UIColor blackColor];
    totalColor.effectRange               = totalRange;
    
    ForegroundColorAttribute *mpsColor   = [ForegroundColorAttribute new];
    mpsColor.color                       = [self mpsColorWithValue:currentValue / 100.f];
    mpsColor.effectRange                 = mpsRange;
    
    ForegroundColorAttribute *numColor   = [ForegroundColorAttribute new];
    numColor.color                       = [self numColorWithValue:currentValue / 100.f];
    numColor.effectRange                 = numberRange;
    
    // Create richString.
    NSMutableAttributedString *richString = [[NSMutableAttributedString alloc] initWithString:totalString];
    [richString addStringAttribute:totalFont];
    [richString addStringAttribute:totalColor];
    [richString addStringAttribute:numberFont];
    [richString addStringAttribute:mpsColor];
    [richString addStringAttribute:numColor];
    
    _label.attributedText = richString;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UIColor *)numColorWithValue:(CGFloat)value {
    
    return [UIColor colorWithRed:value green:0 blue:0 alpha:1.f];
}

- (UIColor *)mpsColorWithValue:(CGFloat)value {
    
    return [UIColor colorWithRed:0 green:value / 2.f blue:value / 3.f alpha:value];
}
- (void)configAnimationArray{
    
}
- (void)configTableView{
    
}
@end
